import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-weightMonitor',
	templateUrl: './weightMonitor.component.html',
	styleUrls: ['./WeightMonitor.css']
})
export class WeightMonitorComponent implements OnInit {
	constructor(private jsonApiService: JsonApiService, private router: Router) {};
	deviceId: string = '';
	carNumber: string = ''; //车辆重量
	carWeight: any = '0.00'; //车辆重量
	weightUnit: string = ' 吨'; //车辆重量单位
	treeStatus: string = '收起'; //树形图展开或者收起状态
	btnDownTime: number = 0; //截留树形图展开关闭频率时间
	weightTimer: any; //监控实时重量的定时器
	circleArr: any[] = []; //测试圆点的长度数组
	isClick: boolean = false;
	isOut: boolean = true;
	noWeightNum: number = 0; //记录定时器获取重量时没有数据的次数,累计到10次关闭定时器
	downTime: number = 1000; //倒计时,单位毫秒
	countDownTimer: any; //倒计时定时器;
	frequency: number = 1;
	befoFrequency: number = 1; //确认设置频率之前

	outWeight: number = 30; //确认设置超出重量之前
	befoOutWeight: number = 30; //确认设置超出重量之前

	weightChart: any; //重量折线图
	echartOption: any; //折线图基础配置 	
	lineColor: string = 'rgba(87, 147, 243, 0.8)'; //折线颜色

	carTreeData = []; //车辆树形图数据
	notOnlineCar = false;
	//初始化树形图数据
	findCarCount = 0; //车辆树搜出的总数
	findCarIndex = 0; //车辆树当前定位
	findString = ''; //搜索提示
	
	
	getCartreeMess(carMess){
		this.slectedCarEvent(carMess);
	}
	//选中一辆车事件
	slectedCarEvent(param) {
		this.deviceId = param.deviceId;
		this.carNumber = param.carNumber;
		this.getNowWeight();
	}
	ngOnInit() {
		for(let i = 0; i < 100; i++) {
			this.circleArr.push('0');
		}
		this.initChartOptions();
		this.addEventWindowResize();
	}
	addEventWindowResize() {
		$(window).on('resize', function() {
			var wrapWidth = $("#wrap").width();
			var divTreeWidth = $(".divTree").width();
			$('.treeRight').width(wrapWidth - divTreeWidth - 24 + 'px');
		})
	}
	draggingEvent() {
		var clickX;
		var warp = $("#wrap");
		var treeElement = $(".divTree");
		var treeRight = $(".treeRight");
		var min = 300;
		var max = 0;
		var leftOffset = warp.offset().left;
		$(document).on('mousemove', function(e) {
			var wrapWidth = warp.width();
			max = wrapWidth / 2;
			var divTreeWidth = treeElement.width();
			var treeRightWidth = treeRight.width();
			clickX = e.pageX;
			//clickX-leftOffset > min   鼠标往右移动,并且大于最小宽度300
			if(clickX - leftOffset > min) {
				if(clickX - leftOffset < max) {
					treeElement.width(clickX - leftOffset + 'px');
					treeRight.width(wrapWidth - clickX + leftOffset - 24 + 'px');
				} else {
					treeElement.width(max + 'px');
					treeRight.width(wrapWidth - max - 24 + 'px');
				}
			} else {
				treeElement.width(min + 'px');
				treeRight.width(wrapWidth - min - 24 + 'px');
			}
		});
		$(document).mouseup(function(e) {
			e.cancelBubble = true;
			$(document).unbind('mousemove')
		})
	}
	//点击列表车辆获取当前车辆重量
	getNowWeight() {
		if(this.deviceId == '') {
			this.isClick = false;
			this.jsonApiService.message('设备编号为空.');
			return;
		}
		this.getWeightUnit();
		let reqdata = 'deviceId=' + this.deviceId;
		this.jsonApiService.http("track/follow.html", reqdata).subscribe(result => {
			//			this.monitorWeightTimer();
			//			return;
			if(result.success) {
				this.carWeight = common.twoDecimal(result.data.weight);
				this.monitorWeightTimer();
			} else {
				this.isClick = false;
				this.jsonApiService.message('未获取到重量数据[设备离线]');
			}
		})
	}
	//获取对应的车辆的重量单位;
	getWeightUnit() {
		var that = this;
		let reqdata = 'deviceId=' + this.deviceId;
		$.ajax({        
			type: "GET",
			data: reqdata,
			    url: config.BaseURL + 'realtime/getRealTimeDataForBase.html',
			    dataType: "json",
			async: false,
			xhrFields: {
				withCredentials: true
			},
			      success: function(result) {
				if(result.data.unit == '2') {
					that.weightUnit = ' 千克';
				} else {
					that.weightUnit = ' 吨';
				}
			}         
		});
	}
	//重置重量监控的定时器
	monitorWeightTimer() {
		if(this.weightTimer) {
			window.clearInterval(this.weightTimer);
		}
		this.isClick = true;
		//		this.showWeightChart();
		let that = this;
		//		that.carWeight=0;
		let reqdata = 'deviceId=' + this.deviceId;
		this.weightTimer = setInterval(function() {
			that.jsonApiService.http2("track/follow.html", reqdata).subscribe(result => {
				//				that.carWeight=that.carWeight+1;
				//				if(that.carWeight>23){
				//					that.carWeight=23;
				//				}
				//				return;
				if(result.success) {
					that.carWeight = common.twoDecimal(result.data.weight);
				} else {
					if(that.noWeightNum > 9) {
						that.noWeightNum = 0;
						window.clearInterval(that.weightTimer);
						that.jsonApiService.message('未获取到重量数据[设备离线]');
						that.isClick = false;
					}
				}
			})
		}, that.frequency * 1000);
	}
	//弹框事件start
	setUp(val) {
		if(this.befoFrequency < 1) {
			this.jsonApiService.message('频率输入有误,请输入大于0的整数值');
			return;
		}
		if(this.befoOutWeight < 0) {
			this.jsonApiService.message('阀值输入有误,请输入大于0的重量值');
			return;
		}
		this.frequency = this.befoFrequency;
		this.outWeight = this.befoOutWeight;
		window.clearInterval(this.weightTimer);
		if(this.deviceId !== '') {
			this.getNowWeight();
		}
		val.hide();
	}

	oppenPopup(val) {
		val.show();
	}
	closePopup(val) {
		val.hide();
		this.befoFrequency = this.frequency;
		this.befoOutWeight = this.outWeight;
	}
	//弹框事件end

	//初始化折线图基础配置
	initChartOptions() {
		this.echartOption = {
			title: {
				left: '2%',
				top: '0px',
				text: ''
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross' //十字星	
				},
			},
			grid: {
				right: '20px',
				left: '15%',
				top: '12px',
				bottom: '32px'
			},
			toolbox: {
				feature: {
					dataView: {
						show: false,
						readOnly: false
					},
					restore: {
						show: false
					},
					saveAsImage: {
						show: false
					}
				}
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				axisLine: {
					lineStyle: {
						color: this.lineColor,
					}
				},
				data: [],
			},
			yAxis: [{
				show: true,
				type: 'value',
				position: 'left',
				min: undefined,
				max: undefined,
				offset: undefined,
				splitLine: {      
					show: false    
				},
				axisLine: {
					lineStyle: {
						color: this.lineColor
					}
				},
				axisLabel: {
					formatter: '{value}'
				}
			}],
			series: [{
				name: '重量',
				type: 'line',
				data: []
			}]

		};

	}
	//重置重量折线图
	showWeightChart() {
		this.weightChart = echarts.init(document.getElementById('weightChart'));
		this.initChartOptions();
		this.weightChart.setOption(this.echartOption, true);
		var nowTime = new Date();
		var startTime = common.getTimeMmss(new Date(nowTime.getTime() - 30 * 1000 * 60)); //设置前30分钟
		var endTime = common.getTimeMmss(nowTime);
		//		let _reqdata = 'deviceId=' + this.deviceId + '&startTime=' + startTime + '&endTime=' + endTime + '&showModify=' + false;
		//写死测试数据
		let _reqdata = 'deviceId=' + this.deviceId + '&startTime=2018-10-18 08:59:00&endTime=2018-10-18 09:07:00&showModify=' + false;

		this.jsonApiService.http("stats/draw.html", _reqdata).subscribe(result => {
			var timeData = [];
			var carSpeedArr = [];
			var weightArr = [];
			var len = result.data.length;
			for(var i = 0; i < len; i++) {
				timeData[i] = result.data[i].uploadDate.split(' ')[1]; //x时间轴数据

				var weight = common.twoDecimal(result.data[i].weight)
				if(weight < 0) weight = 0;
				weightArr.push(weight);
				carSpeedArr.push(result.data[i].speed);
			}
			var passageData = [];
			passageData.push({
				name: '重量（吨）',
				type: 'line',
				borderWidth: 5,
				itemStyle: {
					color: this.lineColor
				},
				data: weightArr,
			})
			this.echartOption.xAxis.data = timeData;
			this.echartOption.series = passageData;
			this.weightChart.setOption(this.echartOption, true);
		})

	}
	//离开页面,关闭所有定时器
	ngOnDestroy() {
		$(document).unbind('keyup'); //移除键盘回车事件
		$(window).unbind('resize'); //移除键盘回车事件
		window.clearInterval(this.weightTimer);
	}
}